import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/bean/check_in_statistics_change_status_type.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/bean/check_in_statistics_change_upload_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_dialog_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_log_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';


/// 打卡记录设置标签弹窗
///
/// @author: zengxiangxi
/// @createTime: 3/25/21 4:54 PM
/// @specialDemand:
class CheckInStatisticsLabelPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CheckInStatisticsLabelPage";

  final String name;

  final CheckInStatisticsChangeStatusType statusType;

  final String backUp;

  final String pageNames;

  final DateTime startTime;

  const CheckInStatisticsLabelPage(
      {Key key, this.name, this.statusType, this.backUp, this.pageNames, this.startTime})
      : super(key: key);

  @override
  _CheckInStatisticsLabelPageState createState() =>
      _CheckInStatisticsLabelPageState();

  ///跳转方法
  static Future<CheckInStatisticsChangeUploadBean> navigatorPushDialog(
      BuildContext context,
      String name,
      CheckInStatisticsChangeStatusType statusType,
      String backUp,String pageNames,DateTime startTime) {
    return VgDialogUtils.showCommonBottomDialog<
            CheckInStatisticsChangeUploadBean>(
        context: context,
        child: CheckInStatisticsLabelPage(
          name: name,
          statusType: statusType,
          backUp: backUp,
          pageNames: pageNames,
          startTime: startTime,
        ));
  }
}

class _CheckInStatisticsLabelPageState
    extends State<CheckInStatisticsLabelPage> {
  TextEditingController _editingController;

  CheckInStatisticsChangeStatusType _currentStatusType;

  ValueNotifier<bool> _isAllowConfirmValueNotifier;


  var _nowDate = DateTime.now();//获取当前时间
  var _endNowDate = DateTime.now();//获取当前时间

  @override
  void initState() {
    super.initState();
    // _nowDate = widget?.startTime ?? DateTime.now();
    _nowDate = DateTime.now();
    _endNowDate = DateTime.now();
    _isAllowConfirmValueNotifier = ValueNotifier(false);
    _editingController = TextEditingController()
      ..text = widget.backUp
      ..addListener(_isAllowChange);
    if(widget.statusType == CheckInStatisticsChangeStatusType.Absence){
      _currentStatusType = CheckInStatisticsChangeStatusType.Leave;
    }else{
      _currentStatusType = widget.statusType;
    }

  }

  @override
  void dispose() {
    // timeEventSubscription?.cancel();
    _isAllowConfirmValueNotifier?.dispose();
    _editingController.removeListener(_isAllowChange);
    _editingController?.dispose();
    super.dispose();
  }

  bool isSameMonth = false;
  bool isEndSameMonth = false;
  @override
  Widget build(BuildContext context) {
    return AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets, //边距（必要）
      duration: const Duration(milliseconds: 100), //时常 （必要）
      child: Container(
          decoration: BoxDecoration(
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              borderRadius:
                  BorderRadius.circular(DEFAULT_BOTTOM_CARD_DIALOG_RADIUS)),
          child: _toMainColumnWidget()),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        _toTitleAndButtonWidget(),
        SizedBox(height: 12),
        _toLabelsWidget(),
        SizedBox(height: 9),
        if(_currentStatusType ==
            CheckInStatisticsChangeStatusType.Absence)
        _toAbsenceLabelsWidget(),
        SizedBox(height: 9),
        _toEditContentWidget(),
        SizedBox(height: 40),
      ],
    );
  }

  Widget _toTitleAndButtonWidget() {
    return Container(
      height: 50,
      child: Row(
        children: <Widget>[
          SizedBox(width: 15),
          Text(
            VgStringUtils.getSplitStr([widget?.name], symbol: "·"),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: Colors.white, fontSize: 17, fontWeight: FontWeight.w600),
          ),
          Spacer(),
          ValueListenableBuilder(
            valueListenable: _isAllowConfirmValueNotifier,
            builder: (BuildContext context, bool isAllow, Widget child) {
              return CommonFixedHeightConfirmButtonWidget(
                isAlive: isAllow,
                width: 76,
                height: 30,
                unSelectBgColor:
                    ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
                selectedBgColor:
                    ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                unSelectTextStyle: TextStyle(
                    color: VgColors.INPUT_BG_COLOR,
                    fontSize: 12,
                    fontWeight: FontWeight.w600),
                selectedTextStyle: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                    fontWeight: FontWeight.w600),
                text: "确定",
                onTap: (){
                  if(!(isAllow ?? false)){
                    return;
                  }
                  RouterUtils.pop(context,result: CheckInStatisticsChangeUploadBean(
                    changeStatusType: _currentStatusType,
                    changeBackUp: _editingController?.text?.trim(),
                    endTime: _endNowDate?.toString()?.substring(0,10),
                    startTime: _nowDate?.toString()?.substring(0,10)
                  ));
                },
              );
            },
          ),
          SizedBox(width: 15),
        ],
      ),
    );
  }

  Widget _toAbsenceLabelsWidget() {
    if(DateTime.now().year ==  _nowDate.year&&
        DateTime.now().month == _nowDate.month &&
        DateTime.now().day == _nowDate.day){
      isSameMonth = true;
    }else isSameMonth = false;
    return AnimatedContainer(
      duration: DEFAULT_ANIM_DURATION,
      height: 40,
      color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      margin: const EdgeInsets.symmetric(horizontal: 15),
      child: Center(
        child: Container(
          child: Row(
            children: <Widget>[
              SizedBox(width: 21,),
              Expanded(
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: (){
                    _cupertinoPicker();
                  },
                  child: Container(
                    child: Row(
                      children: [
                        Text(
                          isSameMonth ? "${_nowDate.toString().substring(0,10)}/今天":"${_nowDate.toString().substring(0,10)}",
                          maxLines: 1,
                          style: TextStyle(
                            color: isSameMonth ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                            :ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                            fontSize: 14,
                          ),
                        ),
                        SizedBox(width: 10,),
                        Image.asset(
                          "images/icon_arrow_down.png",
                          width: 11,
                          color:isEndSameMonth ? ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                              : ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C(),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              // SizedBox(width: 29,),
              Center(
                child: Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.only(right: 21),
                  child: Text(
                    "至",
                    maxLines: 1,
                    style: TextStyle(
                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                      fontSize: 14,
                    ),
                  ),
                ),
              ),
              // SizedBox(width: 32,),
              Expanded(
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: (){
                    isEndSameMonth = true;
                    _endCupertinoPicker();
                    setState(() {

                    });
                  },
                  child: Container(
                    padding: const EdgeInsets.only(left: 32),
                    child: Row(
                      children: <Widget>[
                        Text(
                          isEndSameMonth ? "${_endNowDate.toString().substring(0,10)}" :"选择结束日期",
                          maxLines: 1,
                          style: TextStyle(
                            color:isEndSameMonth ? ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                                : ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C(),
                            fontSize: 14,
                          ),
                        ),
                        SizedBox(width: 10,),
                        Image.asset(
                          "images/icon_arrow_down.png",
                          width: 11,
                          color:isEndSameMonth ? ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                              : ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C(),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _cupertinoPicker(){
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        backgroundColor:
        ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
        cancel: Text('取消', style: TextStyle(color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
        itemTextStyle: TextStyle(color: Colors.white),
      ),
      minDateTime: DateTime.parse('2010-01-01'), //起始日期
      maxDateTime: DateTime.parse(isEndSameMonth ? "${_endNowDate.toString().substring(0,10)}" :'2050-01-01'), //终止日期
      initialDateTime: _nowDate, //当前日期
      dateFormat: 'yyyy-MMMM-dd',  //显示格式
      locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us
      onClose: () => print("----- onClose -----"),
      onCancel: () => print('onCancel'),
      onMonthChangeStartWithFirstDate: true,
      onChange: (dateTime, List<int> index) { //改变的时候
        LogUtils.d(dateTime.toString());
      },
      onConfirm: (dateTime, List<int> index) { //确定的时候
        setState(() {
          if(isEndSameMonth){
            _isAllowConfirmValueNotifier.value = true;
          }
          _nowDate = dateTime;
        });
      },

    );
  }

  _endCupertinoPicker(){
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        backgroundColor:
        ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
        cancel: Text('取消', style: TextStyle(color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
        itemTextStyle: TextStyle(color: Colors.white),
      ),
      minDateTime: DateTime.parse("${_nowDate.toString().substring(0,10)}"), //起始日期
      maxDateTime: DateTime.parse('2050-01-01'), //终止日期
      initialDateTime: _endNowDate, //当前日期
      // pickerMode: DateTimePickerMode.datetime,
      dateFormat: 'yyyy-MMMM-dd',  //显示格式
      locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us
      onClose: () => print("----- onClose -----"),
      onCancel: () => print('onCancel'),
      onMonthChangeStartWithFirstDate: true,
      onChange: (dateTime, List<int> index) { //改变的时候
      LogUtils.d(dateTime.toString());
        // setState(() {
        //   // _endNowDate = dateTime;
        //   _isAllowConfirmValueNotifier.value = true;
        // });
      },
      onConfirm: (dateTime, List<int> index) { //确定的时候
        _isAllowConfirmValueNotifier.value = true;
        setState(() {
          _endNowDate = dateTime;
        });
      },
    );
  }

  Widget _toLabelsWidget() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        children: <Widget>[
          if(widget?.pageNames != "CheckInStatisticsListItemSchoolMenuWidget")
          Expanded(
            child: _SelectLabelWidget(
              isSelected:
                  _currentStatusType == CheckInStatisticsChangeStatusType.GoOut,
              text: "今日外出",
              onTap: () =>
                  _changeStatusType(CheckInStatisticsChangeStatusType.GoOut),
            ),
          ),
          if(widget?.pageNames != "CheckInStatisticsListItemSchoolMenuWidget")
          SizedBox(width: 10),
          Expanded(
            child: _SelectLabelWidget(
              isSelected:
                  _currentStatusType == CheckInStatisticsChangeStatusType.Leave,
              text: "今日请假",
              onTap: () =>
                  _changeStatusType(CheckInStatisticsChangeStatusType.Leave),
            ),
          ),
          SizedBox(width: 10),
          Expanded(
            child: _SelectLabelWidget(
              isSelected: _currentStatusType ==
                  CheckInStatisticsChangeStatusType.Absence,
              text: "长期请假",
              onTap: () {
                _changeStatusType(CheckInStatisticsChangeStatusType.Absence);

              }
            ),
          ),
          // SizedBox(width: 10),
          // Expanded(
          //   child: _SelectLabelWidget(
          //       isSelected: _currentStatusType ==
          //           CheckInStatisticsChangeStatusType.Absence,
          //       text: "手动打卡",
          //       onTap: () {
          //         _changeStatusType(CheckInStatisticsChangeStatusType.Absence);
          //
          //       }
          //   ),
          // ),
        ],
      ),
    );
  }

  void _changeStatusType(CheckInStatisticsChangeStatusType statusType) {
    if (statusType == null) {
      return;
    }
    if (statusType == _currentStatusType) {
      return;
    }
    if(statusType==CheckInStatisticsChangeStatusType.Absence){
    }
    _currentStatusType = statusType;
    _isAllowChange();
    setState(() {});
  }

  Widget _toEditContentWidget() {
    return Container(
        margin: const EdgeInsets.symmetric(horizontal: 15),
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 12),
        decoration: BoxDecoration(
            color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            borderRadius: BorderRadius.circular(4)),
        child: VgTextField(
          controller: _editingController,
          maxLines: 4,
          minLines: 4,
          decoration: InputDecoration(
            border: InputBorder.none,
            counterText: "",
            contentPadding: const EdgeInsets.only(bottom: 2),
            hintText: "备注说明...",
            hintStyle: TextStyle(
                color:
                    ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
                fontSize: 14),
          ),
          style: TextStyle(
              fontSize: 14,
              color: ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
        ));
  }

  ///判断是都允许更改
  void _isAllowChange() {
    if (_currentStatusType != widget.statusType ||
        showOriginEmptyStr(_editingController.text) != showOriginEmptyStr(widget.backUp)) {
      if(_currentStatusType == CheckInStatisticsChangeStatusType.Absence){
        if(isEndSameMonth == false){
          _isAllowConfirmValueNotifier.value = false;
        }
      }else{
        _isAllowConfirmValueNotifier.value = true;
      }
      return;
    }
    _isAllowConfirmValueNotifier.value = false;
  }
}


/// 选择标签组件
///
/// @author: zengxiangxi
/// @createTime: 3/25/21 5:42 PM
/// @specialDemand:
class _SelectLabelWidget extends StatelessWidget {
  final bool isSelected;
  final String text;
  final VoidCallback onTap;

  const _SelectLabelWidget(
      {Key key, this.isSelected = false, this.text, this.onTap})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: onTap,
      child: AnimatedContainer(
        duration: DEFAULT_ANIM_DURATION,
        height: 40,
        decoration: BoxDecoration(
            color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            borderRadius: BorderRadius.circular(4),
            border: isSelected
                ? Border.all(
                    color:
                        ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    width: 1)
                : null),
        child: Center(
          child: AnimatedDefaultTextStyle(
            duration: DEFAULT_ANIM_DURATION,
            style: TextStyle(
              color: isSelected
                  ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  : ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
              fontSize: 14,
            ),
            child: Text(
              text ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
      ),
    );
  }
}